var gameId;

function startNewGame() {
    $('#missed li').remove();
    $('#hidden-word li').remove();
    
    $.post('/game/start').done(function (data) {
        console.log(data);
        loadGameState(data);
    }).fail(function() {
        handleCallFailed();
    });
}

function loadPreviousGame() {
    $.get('/game/load').done(function (data) {
        console.log(data);
        loadGameState(data);
    }).fail(function() {
        handleCallFailed();
    });
}


function loadGameState(state) {
    if($('#inputGroup').is(':hidden')) {
        $('#inputGroup').show();
    }
    updateHangman(state.livesRemaining);

    populateHiddenWordPlaceholder(state.hiddenWordLength);

    var guessedList = [];
    if (typeof state.guessed !== 'undefined') {
         discoverGuessedChars(state.guessed, guessedList);
    }

    if (typeof state.introduced !== 'undefined') {
        populateIntroducedCharsList(state, guessedList);
    }
}

function discoverGuessedChars(guessedLetters, guessedList) {
    for (pair in guessedLetters) {
        var charToDiscover = pair[0];
        var positions = guessedLetters[charToDiscover];
        positions.forEach(function (i) {
            discoverHiddenChar(i, charToDiscover);
        });
        guessedList.push(charToDiscover);
    }
}

function populateHiddenWordPlaceholder(n) {
    var hiddenWord = $('#hidden-word');
    for(var i = 0; i < n; i++) {
        hiddenWord.append($('<li>').append('<span>_</span>'));
    }
}

function populateIntroducedCharsList(state, guessedList) {
    state.introduced.forEach(function (c) {
        var missed = $.inArray(c, guessedList) === -1;
        if(missed) {
            appendCharInMissed(c);
        }
    });
}

function appendCharInMissed(c) {
    var missed = $('#missed');
    missed.append($('<li>', { class : 'missed'}).append($('<span>').text(c)));
}

function postGuess(nextGuess) {
    $.post('/game/guess', { 'guessChar': nextGuess }).done(function (data) {
        console.log(data);
        processResult(data, nextGuess);
    }).fail(function() {
        handleCallFailed();
    });
}

function processResult(guessResult, char) {
    if(guessResult.won) {
        handleWon(char);
    } else if(guessResult.lost) {
        handleLost(guessResult);
    } else {
        if (typeof guessResult.livesRemaining !== 'undefined') {
            $('#livesRemaining').text(guessResult.livesRemaining);
            appendCharInMissed(char);   
            updateHangman(guessResult.livesRemaining);
        }
        if (typeof guessResult.guessedPositions !== 'undefined' && guessResult.guessedPositions.length > 0) {
            var hiddenText = $('#hiddenWord').text();
            guessResult.guessedPositions.forEach(function (i) {
                discoverHiddenChar(i, char);
            });
            $('#hiddenWord').text(hiddenText);
        }
    }
}

function handleWon(char) {
    $('#hidden-word li span').each(function (i, span) {
        if($(span).text() === '_') {
            $(span).text(char);
        } 
    });
    var playAgain = false;
    BootstrapDialog.show({
        title: 'Congratulations!',
        message: 'You\'ve won!',
        buttons: [{
            id: 'btn-ok',    
            label: 'Play again?',
            cssClass: 'btn-primary', 
            autospin: false,
            action: function(dialogRef) { 
                playAgain = true    ;
                dialogRef.close();   
            }
        }],
        onhidden: function(dialogRef) {
            if(playAgain) {
                startNewGame();
            }
        }
    });

    hideInputGroup();
}

function handleLost(guessResult) {
    var playAgain = false;
    BootstrapDialog.show({
        title: 'You\'ve lost!',
        message: 'The word was ' + guessResult.hiddenWord,
        buttons: [{
            id: 'btn-ok',    
            label: 'Play again?',
            cssClass: 'btn-primary', 
            autospin: false,
            action: function(dialogRef) { 
                playAgain = true    ;
                dialogRef.close();   
            }
        }],
        onhidden: function(dialogRef) {
            if(playAgain) {
                startNewGame();
            }
        }
    });
    hideInputGroup();
    updateHangman(0);
}

function updateHangman(livesRemaining) {
    var hangman = $('#hangman');
    if (hangman.is(":hidden") ) {
        hangman.show();
    }
    hangman.attr("src","/resources/img/hm" + livesRemaining + ".png");
}

function discoverHiddenChar(i, char) {
    var nth = i + 1;
    $( "#hidden-word li:nth-child(" + nth + ") span" ).text(char);
};

function hideInputGroup() {
    $('#inputGroup').hide();    
}

function handleCallFailed() {
	BootstrapDialog.show({
		type: BootstrapDialog.TYPE_WARNING,
		title: 'Oops..',
		message: 'Error occurred while dealing with a request, please try again.',
		buttons: [{
            id: 'btn-ok',    
            label: 'ok',
            cssClass: 'btn-primary', 
            autospin: false,
            action: function(dialogRef) {  ;
                dialogRef.close();   
            }
        }]
	});
}